package com.deductive.web.disposition.special;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.deductive.common.core.controller.BaseController;
import com.deductive.common.core.domain.AjaxResult;
import com.deductive.domain.special.SpecialDataTree;
import com.deductive.service.special.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
// import java.util.concurrent.*;
// import java.util.stream.Collectors;


@RestController
@RequestMapping("/desdDateTree")
@Api(tags = "专题目录管理")
public class SpecialDataTreeController extends BaseController {

    @Autowired
    private SpecialDataTreeService desdDataTreeService;
    /**
     * 专题医院服务对象
     */
    @Resource
    private SpecialHospitalService specialHospitalService;

    /**
     * 专题舰艇服务对象
     */
    @Resource
    private SpatialShipService spatialShipService;

    /**
     * 专题机场服务对象
     */
    @Resource
    private SpecialAirportService specialAirportService;
    /**
     * 专题血库服务对象
     */
    @Resource
    private SpecialBloodBankService specialBloodBankService;
    /**
     * 专题港口服务对象
     */
    @Resource
    private SpecialSeaportService specialSeaportService;
    /**
     * 专题卫生防疫机构服务对象
     */
    @Resource
    private SpecialWsfyjgService specialWsfyjgService;

//    @PostMapping("/suspendIcon")
//    @ApiOperation("挂接图标")
//    public AjaxResult suspendIcon() {
//        List<Symbol> list = desdSymbolService.list();
//        for (Symbol desdSymbol : list) {
//            String symbolName = desdSymbol.getSymbolName();
//            String sumbolUrl = desdSymbol.getSumbolUrl();
//            SpecialDataTree desdSpecialData = new SpecialDataTree();
//            desdSpecialData.setName(symbolName);
//            desdSpecialData.setIcon(sumbolUrl);
//            LambdaQueryWrapper<SpecialDataTree> wq = new LambdaQueryWrapper<SpecialDataTree>()
//                    .eq(desdSpecialData.getName() != null, SpecialDataTree::getName, desdSpecialData.getName());
//            desdDataTreeService.update(desdSpecialData, wq);
//        }
//
//        return AjaxResult.success();
//    }

//    @PostMapping("/treeToIcon")
//    @ApiOperation("指定数据挂接图标")
//    public AjaxResult treeToIcon(Integer treeId, String iconUrl) {
//        SpecialDataTree desdDataTree = new SpecialDataTree();
//        desdDataTree.setId(treeId);
//        desdDataTree.setIcon(iconUrl);
//        desdDataTreeService.updateById(desdDataTree);
//        return AjaxResult.success();
//    }


    @GetMapping("/listAll")
    @ApiOperation("数据查询全部")
    public AjaxResult listAll(SpecialDataTree graph) {
//        List<SpecialDataTree> list = desdDataTreeService.listAll(graph);
        LambdaQueryWrapper<SpecialDataTree> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(graph.getName()!=null ,SpecialDataTree::getName,graph.getName());
        wrapper.like(graph.getTableName()!=null ,SpecialDataTree::getTableName,graph.getTableName());
        List<SpecialDataTree> list = desdDataTreeService.list(wrapper);
        return AjaxResult.success(list);
    }


    @GetMapping("/list")
    @ApiOperation("数据树查询")
    public AjaxResult list(SpecialDataTree graph) {
        LambdaQueryWrapper<SpecialDataTree> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(graph.getName()!=null ,SpecialDataTree::getName,graph.getName());
        wrapper.like(graph.getTableName()!=null ,SpecialDataTree::getTableName,graph.getTableName());
        List<SpecialDataTree> list = desdDataTreeService.list(wrapper);
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        treeNodeConfig.setIdKey("id");
        treeNodeConfig.setNameKey("name");
        treeNodeConfig.setParentIdKey("parentId");
        treeNodeConfig.setWeightKey("orderNum");
        List<Tree<Object>> build = TreeUtil.build(list, 0, treeNodeConfig, (map, tree) -> {
            tree.setId(map.getId());
            tree.setName(map.getName());
            tree.setParentId(map.getParentId());
            tree.putExtra("isData", map.getIsData());
            tree.putExtra("tableName", map.getTableName());
            tree.putExtra("dataType", map.getDataType());
            tree.putExtra("count", map.getCount());
            tree.putExtra("icon", map.getIcon());
            tree.putExtra("orderNum", map.getOrderNum());
            tree.putExtra("color", map.getColor());
            tree.putExtra("opacity", map.getOpacity());
            tree.putExtra("visible", map.getVisible());
            tree.putExtra("geoserverUrl", map.getGeoserverUrl());
        });
        if (build == null || build.isEmpty()) {
            // 当没有可用的父子关系时，按平铺返回节点，避免返回空
            List<Tree<Object>> flat = new ArrayList<>();
            for (SpecialDataTree map : list) {
                Tree<Object> tree = new Tree<>();
                tree.setId(map.getId());
                tree.setName(map.getName());
                tree.setParentId(map.getParentId());
                tree.putExtra("isData", map.getIsData());
                tree.putExtra("tableName", map.getTableName());
                tree.putExtra("dataType", map.getDataType());
                tree.putExtra("count", map.getCount());
                tree.putExtra("icon", map.getIcon());
                tree.putExtra("orderNum", map.getOrderNum());
                tree.putExtra("color", map.getColor());
                tree.putExtra("opacity", map.getOpacity());
                tree.putExtra("visible", map.getVisible());
                tree.putExtra("geoserverUrl", map.getGeoserverUrl());
                flat.add(tree);
            }
            return AjaxResult.success(flat);
        }
        return AjaxResult.success(build);
    }


    @GetMapping("/listAllSpecialData")
    @ApiOperation("专题数据树查询")
    public AjaxResult listAllSpecialData() {
        List<SpecialDataTree> list = desdDataTreeService.list();
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        treeNodeConfig.setIdKey("id");
        treeNodeConfig.setNameKey("name");
        treeNodeConfig.setParentIdKey("parentId");
        treeNodeConfig.setWeightKey("orderNum");
        List<Tree<Object>> build = TreeUtil.build(list, 0, treeNodeConfig, (map, tree) -> {
            tree.setId(map.getId());
            tree.setName(map.getName());
            tree.setParentId(map.getParentId());
            tree.putExtra("isData", map.getIsData());
            tree.putExtra("tableName", map.getTableName());
            tree.putExtra("dataType", map.getDataType());
            tree.putExtra("count", map.getCount());
            tree.putExtra("icon", map.getIcon());
            tree.putExtra("orderNum", map.getOrderNum());
            tree.putExtra("color", map.getColor());
            tree.putExtra("opacity", map.getOpacity());
            tree.putExtra("visible", map.getVisible());
            tree.putExtra("geoserverUrl", map.getGeoserverUrl());
        });

        for (Tree<Object> treeNode : build) {
            if (treeNode.getChildren()!=null) {
                for (Tree<Object> node : treeNode.getChildren()) {
                    Object tableName = node.get("tableName"); // 根据 Tree 的实际实现调整获取方式
                    if (tableName != null) {
                        String nodeTableName=tableName.toString();
                        switch (nodeTableName) {
                            case "special_hospital":
                                node.setChildren(this.specialHospitalService.listTree());
                                break;
                            case "special_blood_bank":
                                node.setChildren(this.specialBloodBankService.listTree());
                                break;
                            case "special_seaport":
                                node.setChildren(this.specialSeaportService.listTree());
                                break;
                            case "special_wsfyjg":
                                node.setChildren(this.specialWsfyjgService.listTree());
                                break;
                            case "special_airport":
                                node.setChildren(this.specialAirportService.listTree());
                                break;
                            case "spatial_ship":
                                node.setChildren(this.spatialShipService.listTree());
                                break;
                        }
                    }
                }
            }

        }
        return AjaxResult.success(build);
    }


//    @PostMapping("/querySpecialData")
//    @ApiOperation("专题数据查询")
//    public AjaxResult querySpecialData() {
//        SpecialDataTree graph = new SpecialDataTree();
//        graph.setIsData(1);
//
//        LambdaQueryWrapper<SpecialDataTree> eq = new LambdaQueryWrapper<SpecialDataTree>()
//                .eq(graph.getIsData() != null, SpecialDataTree::getIsData, graph.getIsData());
//        List<SpecialDataTree> treeList = desdDataTreeService.list(eq);
//
//        List<SpecialData> list = null;
//        if (treeList.size() > 0) {
//            List<String> tableNames = treeList.stream().map(SpecialDataTree::getTableName).collect(Collectors.toList());
//            LambdaQueryWrapper<SpecialData> specialDataLambdaQueryWrapper = new LambdaQueryWrapper<>();
//            specialDataLambdaQueryWrapper.notIn(SpecialData::getTableName, tableNames).
//                    orderByAsc(true, SpecialData::getTableName);
//            list = desdSpecialDataService.list(specialDataLambdaQueryWrapper);
//        } else {
//            list = desdSpecialDataService.list();
//        }
//        return AjaxResult.success(list);
//    }


//    @PostMapping("/bindSpecialData")
//    @ApiOperation("绑定专题数据")
//    public AjaxResult bindSpecialData(@RequestBody List<SpecialData> specialDatas) {
//        List<SpecialDataTree> desdDataTrees = new ArrayList<>();
//        for (SpecialData specialData : specialDatas) {
//
//            String tableName = specialData.getTableName();
//            String dataType = specialData.getDataType();
//            Long count = specialData.getCount();
//            String icon = specialData.getIcon();
//            String geoserverUrl = specialData.getGeoserverUrl();
//            Integer parentId = specialData.getParentId();
//
//            SpecialDataTree desdDataTree = new SpecialDataTree();
//            desdDataTree.setName(tableName);
//            desdDataTree.setTableName(tableName);
//            desdDataTree.setDataType(dataType);
//            desdDataTree.setGeoserverUrl(geoserverUrl);
//            desdDataTree.setCount(count);
//            desdDataTree.setIsData(1);
//            desdDataTree.setVisible(1L);
//            desdDataTree.setIcon(icon);
//            desdDataTree.setParentId(parentId);
//            desdDataTrees.add(desdDataTree);
//        }
//        boolean b = desdDataTreeService.saveOrUpdateBatch(desdDataTrees);
//        return AjaxResult.success(b);
//    }


//    @PostMapping("/queryDynamicByRegion")
//    @ApiOperation("动态区域查询")
//    public AjaxResult queryDynamicByRegion(String geomjson, String tableNames, String keyword) throws InterruptedException {
//        if (geomjson == null) {
//            throw new RuntimeException("区域不能为空");
//        }
//        if (tableNames == null) {
//            throw new RuntimeException("查询的数据不能为空");
//        }
//        List<String> tableNameList = new ArrayList<>();
//        if (tableNames.contains(",")) {
//            String[] split = tableNames.split(",");
//            tableNameList.addAll(Arrays.asList(split));
//        } else {
//            tableNameList.add(tableNames);
//        }
//        LambdaQueryWrapper<SpecialDataTree> treeEQ = new LambdaQueryWrapper<SpecialDataTree>()
//                .in(SpecialDataTree::getName, tableNameList);
//        List<SpecialDataTree> treeList = desdDataTreeService.list(treeEQ);
//        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(20, 40, 60, TimeUnit.SECONDS, new LinkedBlockingDeque<>());
//        CountDownLatch countDownLatch = new CountDownLatch(treeList.size());
//        List<JSONObject> list = new ArrayList<>();
//        for (SpecialDataTree desdDataTree : treeList) {
//            String tableName = desdDataTree.getName();
//            threadPoolExecutor.submit(() -> {
//                List<JSONObject> columns = pgDBMapper.getColumns(tableName);
//                //拼接查询参数
//                StringBuilder builder = new StringBuilder();
//                builder.append("select ");
//                //循环拼接参数
//                for (JSONObject column : columns) {
//                    String columnName = (String) column.get("column_name");
//
//                    if (columnName.equals("geom")) {
//                        builder.append("st_asgeojson(").append(columnName).append(") as geom ,");
//                    } else {
//                        builder.append(columnName).append(", ");
//                    }
//                }
//                builder.delete(builder.length() - 2, builder.length());
//                builder.append(" from ").append("\"" + tableName + "\" where  ST_Intersects(ST_GeomFromGeoJSON('" + geomjson + "'),geom)");
//                List<JSONObject> jsonObjects = pgDBMapper.selectDataDynamic(builder.toString());
//                list.addAll(jsonObjects);
//                countDownLatch.countDown();
//            });
//        }
//        threadPoolExecutor.shutdown();
//        countDownLatch.await();
//        return AjaxResult.success(list);
//    }

    //    @PreAuthorize("@ss.hasPermi('be:date_tree:list')")
//    @GetMapping("/queryDynamicCountByRegion")
//    @ApiOperation("动态区域统计")
//    public AjaxResult queryDynamicCountByRegion(@RequestParam String geomjson, String tableNames) throws InterruptedException {
//
//        if (geomjson == null) {
//            throw new RuntimeException("区域不能为空");
//        }
//        String[] split = geomjson.split(",");
//        StringBuilder builder1 = new StringBuilder();
//        for (String s : split) {
//            builder1.append("[" + s.split("_")[0]).append(",").append(s.split("_")[1]).append("],");
//        }
//        builder1.setLength(builder1.length() - 1);
//        String format = String.format("{\"type\":\"MultiPolygon\",\"crs\":{\"type\":\"name\",\"properties\":{\"name\":\"EPSG:4490\"}},\"coordinates\":[[[%s]]]}", builder1.toString());
//
//        LambdaQueryWrapper<SpecialDataTree> treeEQ = new LambdaQueryWrapper<SpecialDataTree>()
//                .eq(true, SpecialDataTree::getVisible, 1L)
//                .eq(SpecialDataTree::getDataType, "点");
//        List<SpecialDataTree> treeList = desdDataTreeService.list(treeEQ);
//
//
//        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(20, 40, 60, TimeUnit.SECONDS, new LinkedBlockingDeque<>());
//        CountDownLatch countDownLatch = new CountDownLatch(treeList.size());
//        List<JSONObject> list = new ArrayList<>();
//        for (SpecialDataTree desdDataTree : treeList) {
//            String tableName = desdDataTree.getName();
//            threadPoolExecutor.submit(() -> {
//                //拼接查询参数
//                StringBuilder builder = new StringBuilder();
//                builder.append("select count(*) count ");
//
//                builder.append(" from ").append("\"" + tableName + "\" where  ST_Intersects(ST_GeomFromGeoJSON('" + format + "'),geom)");
//                JSONObject jsonObject = pgDBMapper.selectDataDynamicCount(builder.toString());
//                jsonObject.put("name", tableName);
//                list.add(jsonObject);
//                countDownLatch.countDown();
//            });
//        }
//        countDownLatch.await();
//        return AjaxResult.success(list);
//    }


//    /**
//     * 获取图谱维护详细信息
//     */
//    @GetMapping(value = "/{id}")
//    @ApiOperation("根据Id查询")
//    public AjaxResult getInfo(@PathVariable("id") String id) {
//        return AjaxResult.success(desdDataTreeService.getById(id));
//    }
//

    @PostMapping
    @ApiOperation("添加数据")
    public AjaxResult add(@RequestBody SpecialDataTree graph) {
        graph.setVisible(1L);
        boolean save = desdDataTreeService.save(graph);
        return toAjax(save);
    }


    @PutMapping("/edit")
    @ApiOperation("修改数据")
    public AjaxResult edit(@RequestBody SpecialDataTree graph) {
        boolean b = desdDataTreeService.updateById(graph);
        return toAjax(b);
    }


    @DeleteMapping
    @ApiOperation("删除数据")
    public AjaxResult delete(@RequestParam("idList") List<Long> idList) {
        return success(this.desdDataTreeService.removeByIds(idList));
    }

}
